package com.jzl.util;


import com.squareup.okhttp.*;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;


public class HttpClient
{
    /**
     *  数据编码格式
     */
    public static final MediaType JSON_MTYPE = MediaType.parse("application/xml; charset=utf-8");
    public static final MediaType XMLMTYPE = MediaType.parse("application/xml; charset=utf-8");

    private static final OkHttpClient client = new OkHttpClient();

    static
    {
        client.setConnectTimeout(30, TimeUnit.SECONDS);
        client.setReadTimeout(30, TimeUnit.SECONDS);
        client.setWriteTimeout(30, TimeUnit.SECONDS);
    }

    public String postByJson(String content, String url) throws IOException
    {

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), content);
        Request request = new Request.Builder().url(url).post(requestBody).build();
        com.jzl.util.LoggerUtil.info(String.format("OkHttp[json]-request->%s\n%s", url, content));
        Response response = client.newCall(request).execute();
        String res = response.body().string();
        LoggerUtil.info(String.format("OkHttp[json]-response->%s\n%s", url, res));
        return res;
    }

    public Response postByForm(String url, Map<String, Object> header, Map<String, Object> params) throws IOException
    {
        RequestBody requestBody = getFormBody(params);
        Request.Builder builder = new Request.Builder();
        for (String key : header.keySet())
        {
            builder.addHeader(key, (String) header.get(key));
        }
        Request request = builder.url(url).post(requestBody)
                .build();
        return client.newCall(request).execute();
    }

    private RequestBody getFormBody(Map<String, Object> params)
    {
        FormEncodingBuilder builder = new FormEncodingBuilder();
        for (String key : params.keySet())
        {
            builder.add(key, (String) params.get(key));
        }
        return builder.build();
    }

    public String get(String url) throws IOException
    {
        Request request = new Request.Builder().url(url).get().build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    public Response get(String url, Map<String, String> header) throws IOException
    {
        Request.Builder builder = new Request.Builder();
        for (String key : header.keySet())
        {
            builder.addHeader(key, header.get(key));
        }
        Request request = builder.url(url).get()
                .build();
        return client.newCall(request).execute();
    }


}